package com.xjrsoft.module.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xjrsoft.module.system.dto.ErpConfigDto;
import com.xjrsoft.module.system.entity.ErpConfig;
import com.xjrsoft.module.system.mapper.ErpConfigMapper;
import com.xjrsoft.module.system.service.IErpConfigService;
import com.xjrsoft.module.system.model.ErpConfigModel;
import com.kingdee.bos.webapi.sdk.K3CloudApi;
import com.kingdee.bos.webapi.entity.IdentifyInfo;
import cn.hutool.json.JSONUtil;
import com.xjrsoft.common.enums.ErpConfigEnum;

import org.springframework.stereotype.Service;

/**
 * @Author: lxl
 * @Date: 2024/6/25 14:12
 */
@Service
public class ErpConfigServiceImpl  extends ServiceImpl<ErpConfigMapper, ErpConfig> implements IErpConfigService {


    @Override
    public boolean updateErpConfig(ErpConfigDto dto) {

        long count = this.count(Wrappers.lambdaQuery(ErpConfig.class).eq(ErpConfig::getErpType, dto.getErpType()));
        ErpConfig erpConfig = BeanUtil.toBean(dto, ErpConfig.class);
        //如果存在 就代表此配置存在数据库  只需要修改
        if(count > 0){
            this.update(erpConfig,Wrappers.lambdaQuery(ErpConfig.class).eq(ErpConfig::getErpType, dto.getErpType()));
        }
        else {
            this.save(erpConfig);
        }
        return true;
    }
    public String execErp(String param)
    {
        String  erpConfigJson = this.getOne(Wrappers.lambdaQuery(ErpConfig.class).eq(ErpConfig::getErpType, ErpConfigEnum.KINGDEE)).getConfigJson();
        ErpConfigModel erpConfig = JSONUtil.toBean(erpConfigJson, ErpConfigModel.class);
        
        IdentifyInfo identi = new IdentifyInfo();
        identi.setAppId(erpConfig.getAppId());//应用ID
        identi.setUserName(erpConfig.getUserName());//用户名
        identi.setPwd(erpConfig.getPassword());//密码
        identi.setServerUrl(erpConfig.getUrl());//服务地址
        //identi.setAppSecret("bc49a1b59cd443e3851d83a52dbe6e48");//密钥，也可用密码参数
        identi.setdCID(erpConfig.getDbId());//账套ID，这里可以改成变量，前端界面上放个下拉框
        identi.setOrgNum("100");
        K3CloudApi api = new K3CloudApi(identi);
    

        String resultJson = "";

        try {
            //调用接口
            resultJson = String.valueOf(api.executeBillQuery(param));
            System.out.println("接口返回结果: " + resultJson);
        } catch (Exception e) {
            //fail(e.getMessage());
            resultJson=e.getMessage();
        }
        return resultJson;
    } 
}
